package com.burst.reptile.framework.security.service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.burst.reptile.common.utils.ToolUtil;
import com.burst.reptile.modular.system.entity.SysMenu;
import com.burst.reptile.modular.system.entity.SysUser;
import com.burst.reptile.modular.system.service.ISysMenuService;
import com.burst.reptile.modular.system.service.ISysRoleService;

import lombok.RequiredArgsConstructor;

/**
 * 用户权限处理
 * @author wujin
 *
 * @date: 2020-9-16 13:04:48
 */
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysPermissionService {
	
	private final ISysRoleService roleService;

	private final ISysMenuService menuService;

	/**
	 * 获取角色数据权限
	 * 
	 * @param user 用户信息
	 * @return 角色权限信息
	 */
	public Set<String> getRolePermission(SysUser user) {
		Set<String> roles = new HashSet<String>();
		// 管理员拥有所有权限
		if (user.isAdmin()) {
			roles.add("admin");
		} else {
			roles.addAll(roleService.selectRolePermissionByUserId(user.getUserId()));
		}
		return roles;
	}

	/**
	 * 获取菜单数据权限
	 * 
	 * @param user 用户信息
	 * @return 菜单权限信息
	 */
	public Set<String> getMenuPermission(SysUser user) {
		Set<String> perms = new HashSet<String>();
		// 管理员拥有所有权限
		if (user.isAdmin()) {
//			perms.add("*:*:*");
			List<SysMenu> list = menuService.list(new QueryWrapper<SysMenu>().select("perms").isNotNull("perms"));
			if(ToolUtil.isNotEmpty(list)) {
				Set<String> collect = list.stream().map(SysMenu::getPerms).collect(Collectors.toSet());
				perms.addAll(collect);
			}
		} else {
			perms.addAll(menuService.selectMenuPermsByUserId(user.getUserId()));
		}
		return perms;
	}
}
